package com.nulldev.util.web.nTube.pages;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpClient.util.HttpStreamUtil;

class LocalProcessingRequest implements Closeable {
	private final Object _conn;

	public LocalProcessingRequest(final HttpURLConnection conn) {
		this._conn = conn;
	}

	@SuppressWarnings("unchecked")
	public int code() {
		if (this._conn instanceof HttpURLConnection) {
			try {
				return ((HttpURLConnection) this._conn).getResponseCode();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} else {
			return ((HttpResponse<InputStream>) this._conn).status();
		}
	}

	public LocalProcessingRequest(final HttpResponse<InputStream> conn) {
		this._conn = conn;
	}

	@SuppressWarnings("unchecked")
	public InputStream getResponse() throws Exception {
		if (this._conn instanceof HttpURLConnection) {
			final HttpURLConnection conn = (HttpURLConnection) this._conn;
			final String encoding = conn.getContentEncoding();
			InputStream output;
			try {
				output = HttpStreamUtil.decode(conn.getInputStream(), encoding);
			} catch (IOException exception) {
				output = conn.getErrorStream();
			}
			return output;
		} else {
			return ((HttpResponse<InputStream>) this._conn).data();
		}
	}

	public Object get() {
		return this._conn;
	}

	@Override
	public void close() throws IOException {
		if (this._conn instanceof HttpURLConnection) {
			((HttpURLConnection) this._conn).disconnect();
		}
	}
}
